package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"shang/models"
)

type FriendController struct {
	beego.Controller
}

func (f *FriendController) Friend() {
	userId, _ := f.GetInt("id")
	friendId, _ := f.GetInt("friend_id")
	if userId == friendId {
		f.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "自己不能添加自己为好友",
		}
		f.ServeJSON()
		return
	}
	user, _ := models.GetFriendInfo(models.FriendTwo{
		UserId:   userId,
		FriendId: friendId,
	})
	friend, _ := models.GetFriendInfo(models.FriendTwo{
		UserId:   friendId,
		FriendId: userId,
	})
	if user.ID != 0 && friend.ID != 0 {
		f.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "你们已经添加过好友",
		}
		f.ServeJSON()
		return
	}
	_, err := models.CreateFriend(models.FriendTwo{
		UserId:   userId,
		FriendId: friendId,
	})
	_, err1 := models.CreateFriend(models.FriendTwo{
		UserId:   friendId,
		FriendId: userId,
	})
	if err != nil && err1 != nil {
		f.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "添加好友失败",
		}
		f.ServeJSON()
		return
	}
	f.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	f.ServeJSON()
}
